package com.bw.a2209clubshop.ui.login

import android.graphics.Color
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Lifecycle
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.bw.a2209clubshop.R
import com.bw.a2209clubshop.appContext
import com.bw.a2209clubshop.base.BaseActivity
import com.bw.a2209clubshop.base.BaseFragment
import com.bw.a2209clubshop.base.state.Default
import com.bw.a2209clubshop.base.state.Empty
import com.bw.a2209clubshop.base.state.Failed
import com.bw.a2209clubshop.base.state.Loading
import com.bw.a2209clubshop.base.state.Success
import com.bw.a2209clubshop.databinding.FragmentAccountLoginBinding
import com.bw.a2209clubshop.getAttrValue
import com.bw.a2209clubshop.observeWithLifecycle
import com.bw.a2209clubshop.ui.login.viewModel.LoginViewModel
import com.bw.a2209clubshop.utils.Router.Ui.CommonWebActivity
import com.bw.a2209clubshop.utils.ToastUtils
import com.bw.a2209clubshop.utils.ValidUtil
import dagger.hilt.android.AndroidEntryPoint


@AndroidEntryPoint
class AccountLoginFragment : BaseFragment<LoginViewModel, FragmentAccountLoginBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.fragment_account_login
    private val mViewModel: LoginViewModel by activityViewModels()
    private lateinit var mNavController: NavController
    private var mLoginAgreement: Boolean = false
    override fun initView() {
        mViewModel.setShowingFragmentTag(AccountLoginFragment::class.simpleName!!)
        mNavController = Navigation.findNavController(mBinding.root)
        initAgreementView()
        initAgreementCheckBox(mLoginAgreement)
    }

    override fun initListener() {
        super.initListener()
        mBinding.tvForgetPassword.setOnClickListener {
            mNavController.navigate(R.id.action_accountLoginFragment_to_forgetPsdFragment)
        }

        mBinding.vChecked.setOnClickListener {
            mLoginAgreement = !mLoginAgreement
            initAgreementCheckBox(mLoginAgreement)
        }

        mBinding.btnLogin.setOnClickListener {
            if (checkAccount()) {
                hideSoftKeyBroad(mBinding.etPassword)
                //账号密码登录
                mViewModel.loginByAccount()
            }
        }

        mViewModel.requestLoginEvent.observeWithLifecycle(this, Lifecycle.State.STARTED) {
            when (it) {
                is Success -> {
//                    (activity as? LoginActivity)?.handleLoginSuccess()
                    setLoadingViewVisible(false)
                }
                is Loading -> {
                    setLoadingViewVisible(true)
                }
                is Failed -> {
                    ToastUtils.showShort(requireContext(), it.message)
                    setLoadingViewVisible(false)
                }

                Default -> {}
                Empty -> {}
            }
        }
    }
    //隐私政策Check背景切换
    private fun initAgreementCheckBox(checked: Boolean) {
        if (!checked) {
            mBinding.btnCheck.background = ContextCompat.getDrawable(appContext, R.mipmap.icon_uncheck)
        } else {
//            mPopupAgreement.dismiss()
            mBinding.btnCheck.background = ContextCompat.getDrawable(appContext, R.mipmap.icon_checked)
        }
    }

    //用户协议 隐私政策
    private fun initAgreementView() {
        val colorMain = getAttrValue(requireContext(), R.attr.colorTheme)
        val userAgreement = "《用户协议》"
        val privacyPolicy = "《隐私政策》"
        val content = "阅读并同意$userAgreement 和$privacyPolicy"
        val spannableStringBuilder = SpannableStringBuilder(content)
        val userAgreementStart = content.indexOf(userAgreement)
        val userAgreementEnd = userAgreementStart + userAgreement.length

        val privacyPolicyStart = content.indexOf(privacyPolicy)
        val privacyPolicyEnd = privacyPolicyStart + privacyPolicy.length

        spannableStringBuilder.setSpan(object : ClickableSpan() {
            override fun onClick(p0: View) {
//                CommonWebActivity.jumpUserAgreement()
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color = ContextCompat.getColor(requireContext(), colorMain)
                ds.isUnderlineText = false
            }

        }, userAgreementStart, userAgreementEnd, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
        spannableStringBuilder.setSpan(object : ClickableSpan() {
            override fun onClick(p0: View) {
//                CommonWebActivity.jumpPrivacyAgreement()
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color = ContextCompat.getColor(requireContext(), colorMain)
                ds.isUnderlineText = false
            }

        }, privacyPolicyStart, privacyPolicyEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

        mBinding.tvAgreement.highlightColor = Color.TRANSPARENT
        mBinding.tvAgreement.text = spannableStringBuilder
        mBinding.tvAgreement.movementMethod = LinkMovementMethod.getInstance()
    }

    private fun checkAccount(): Boolean {
        val phone = mViewModel.phone.value
        if (!mLoginAgreement) {
            (activity as BaseActivity<*, *>?)?.dismissKeyboardShortcutsHelper()
            // ToastUtils.showShort(context, "请勾选协议")
//            mPopupAgreement.show(mBinding.btnCheck)
            return false
        }
        if (!ValidUtil.phoneNumberValid(phone)) {
            ToastUtils.showShort(context, "手机号码长度错误")
            return false
        }
//        if (!ValidUtil.isMobile(phone)) {
//            ToastUtils.showShort(context, "手机号码格式错误")
//            return false
//        }
        return true
    }

    override fun initData() {
        mBinding.viewModel = mViewModel
        mViewModel.clearPassword()
    }


}